import tkinter as tk
from tkinter import messagebox
import pyperclip
import time
import pyautogui  # 用于模拟键盘操作
import re  # 用于正则表达式匹配
import pystray  # 用于系统托盘图标
from PIL import Image, ImageDraw, ImageTk  # 用于创建托盘图标
import threading

# 定义保存历史记录的文本文件
HISTORY_FILE = "clipboard_history.txt"

# 使用普通列表代替 deque
history = []

def save_to_history(content):
    """将剪贴板内容保存到历史记录中"""
    if content and content not in [item.split(" - ", 1)[1] for item in history]:
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        history_item = f"{timestamp} - {content}"
        history.append(history_item)
        with open(HISTORY_FILE, "a", encoding="utf-8") as file:
            file.write(f"{history_item}\n")  # 将内容追加到文件中
        update_history_listbox()  # 更新历史记录列表

def load_history():
    """从文件中加载历史记录"""
    try:
        with open(HISTORY_FILE, "r", encoding="utf-8") as file:
            content = file.read()
            # 使用正则表达式按时间戳分割内容
            pattern = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} - ")
            items = pattern.split(content)
            timestamps = pattern.findall(content)
            return [f"{ts}{item.strip()}" for ts, item in zip(timestamps, items[1:])]
    except FileNotFoundError:
        return []  # 如果文件不存在，返回空列表

def update_history_listbox():
    """更新历史记录列表的显示"""
    history_listbox.delete(0, tk.END)  # 清空当前列表
    for item in reversed(history):  # 倒序插入历史记录
        history_listbox.insert(tk.END, item)

def on_item_select(event):
    """当用户点击某条记录时，将其内容粘贴到当前光标聚焦的文本框"""
    selected_index = history_listbox.curselection()  # 获取选中的索引
    if selected_index:
        selected_content = history_listbox.get(selected_index)  # 获取选中的内容
        content = selected_content.split(" - ", 1)[1]  # 提取实际内容
        pyperclip.copy(content)  # 将内容复制到剪贴板
        time.sleep(0.1)  # 等待剪贴板更新

        # 将焦点返回到原来的窗口
        root.after(100, lambda: paste_to_focused_window(content))

def paste_to_focused_window(content):
    """将内容粘贴到当前焦点所在的窗口"""
    try:
        # 模拟按下 Alt+Tab 切换回原来的窗口
        pyautogui.hotkey("alt", "tab")
        time.sleep(0.5)  # 增加等待窗口切换完成的时间

        # 模拟按下 Ctrl+V 粘贴
        pyautogui.hotkey("ctrl", "v")
        time.sleep(0.1)  # 增加粘贴操作后的等待时间
        # messagebox.showinfo("已粘贴", f"已粘贴：\n{content}")
    except Exception as e:
        # messagebox.showerror("错误", f"粘贴失败：{e}")
        pass

def toggle_topmost():
    """切换窗口置顶状态"""
    is_topmost = var_topmost.get()
    root.wm_attributes("-topmost", is_topmost)  # 设置窗口是否置顶

def clear_history():
    """清除剪贴板历史记录"""
    history.clear()  # 清空历史记录列表
    update_history_listbox()  # 更新历史记录列表
    with open(HISTORY_FILE, "w", encoding="utf-8") as file:
        file.write("")  # 清空文件内容
    messagebox.showinfo("清理完成", "剪贴板历史记录已清空")

def monitor_clipboard():
    """监控剪贴板内容的变化"""
    last_content = pyperclip.paste()
    save_to_history(last_content)

    while True:
        time.sleep(1)  # 每隔1秒检查一次剪贴板
        current_content = pyperclip.paste()
        if current_content != last_content:
            last_content = current_content
            save_to_history(current_content)
        root.update()  # 更新GUI界面

def minimize_to_tray():
    """最小化窗口到系统托盘"""
    root.withdraw()  # 隐藏窗口
    create_tray_icon()

def create_tray_icon():
    """创建系统托盘图标"""
    icon_image = Image.open("window-clipboard.ico")
    icon = pystray.Icon("clipboard_history", icon_image, "Clipboard History", menu=pystray.Menu(
        pystray.MenuItem("显示", restore_window),
        pystray.MenuItem("退出", exit_app)
    ))
    icon.run()

def restore_window(icon, item):
    """从系统托盘还原窗口"""
    icon.stop()
    root.deiconify()  # 显示窗口
    root.lift()  # 将窗口置于顶层
    root.focus_force()  # 强制窗口获取焦点

def exit_app(icon, item):
    """退出应用程序"""
    icon.stop()
    root.quit()

# 初始化Tkinter窗口
root = tk.Tk()
root.title("剪贴板历史记录")
root.geometry("400x350")

# 设置窗口图标
root.iconbitmap("window-clipboard.ico")

# 绑定窗口关闭事件
root.protocol("WM_DELETE_WINDOW", minimize_to_tray)

# 创建历史记录列表
history_listbox = tk.Listbox(root, selectmode=tk.SINGLE)
history_listbox.pack(fill=tk.BOTH, expand=True)

# 绑定点击事件
history_listbox.bind("<<ListboxSelect>>", on_item_select)

# 加载历史记录
history.extend(load_history())
update_history_listbox()

# 创建置顶开关
var_topmost = tk.BooleanVar(value=True)  # 默认置顶
topmost_checkbutton = tk.Checkbutton(
    root,
    text="窗口置顶",
    variable=var_topmost,
    command=toggle_topmost
)
topmost_checkbutton.pack(pady=10)
root.wm_attributes("-topmost", True)  # 设置窗口置顶

# 创建清理历史记录按钮
clear_button = tk.Button(
    root,
    text="清理记录",
    command=clear_history
)
clear_button.pack(pady=10)

# 启动剪贴板监控
clipboard_thread = threading.Thread(target=monitor_clipboard, daemon=True)
clipboard_thread.start()

# 运行Tkinter主循环
root.mainloop()